        //
//  XiangQuHttpClient.m
//  XiangQu
//
//  Created by yandi on 14/10/24.
//  Copyright (c) 2014年 Qiuyin. All rights reserved.
//

#import "XiangQuHttpClient.h"
#import "XiangQuBaseParser.h"
#import "XiangQuParserFactory.h"

@interface XiangQuHttpClient ()

@end

static char *loadingmoreKey;
@implementation XiangQuHttpClient

#pragma mark -override initWithBaseURL
- (instancetype)initWithBaseURL:(NSURL *)url {
    if (self  = [super initWithBaseURL:url]) {
        self.requestSerializer.timeoutInterval = 20.;
        [self.requestSerializer setValue:[self.class actionCustomUsrAgent] forHTTPHeaderField:@"User-Agent"];
    }
    return self;
}

#pragma mark -actionCistomUsrAgent
+ (NSString *)actionCustomUsrAgent {
    NSBundle *mainBundle = [NSBundle mainBundle];
    
    NSString *app_ver = [mainBundle.infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *build_ver = [mainBundle.infoDictionary objectForKey:(NSString *)kCFBundleVersionKey];
    
    NSString *channel = ([build_ver intValue] % 2) ? @"ourtech" : @"appStore";

    NSString *currentUserId = [USERDEFAULT objectForKey:kUsrId];
    NSString *userId = @"";
    if (currentUserId) {
        userId = [NSString stringWithFormat:@"UID/%d ",currentUserId.intValue];
    }
    
    NSString *deviceName = @"iPhone";
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        deviceName = @"iPad";
    }
    return [NSString stringWithFormat:@"( Xiangqu; Client/%@%@ V/%@|%@ channel/%@ %@)"
            ,deviceName ,[UIDevice currentDevice].systemVersion , build_ver, app_ver, channel, userId];
}

#pragma mark -requestWithURL
- (AFHTTPRequestOperation *)requestWithURL:(NSString *)url
                                     paras:(NSMutableDictionary *)parasDict
                                   success:(void(^)(AFHTTPRequestOperation *operation,NSObject *parserObject))success
                                   failure:(void(^)(AFHTTPRequestOperation *operation,NSError *requestErr))failure {
    
    NSMutableDictionary *transferParas = [parasDict mutableCopy];
    
    // Loading
    BOOL noLoading = [[transferParas objectForKey:kNoLoading] boolValue];
    [transferParas removeObjectForKey:kNoLoading];
    if (!noLoading) {
        // show hud
        [[XiangQuToastManager manager] showprogress];
    }
    
    // host Change
    BOOL fromHotShop = [[transferParas objectForKey:KHotShopURL] boolValue];
    NSString *hostURL = [XiangQuTool hostsHandlerUnderHostShop:fromHotShop];
    [transferParas removeObjectForKey:KHotShopURL];
    
    // refresh or LoadingMore
    BOOL isLoadingMore = [[transferParas objectForKey:kLoadingMore] boolValue];
    [transferParas removeObjectForKey:kLoadingMore];
    
    // about Order
    NSUInteger orderType = 0;
    if ([url isEqualToString:getToken_URL] || [url isEqualToString:order_URL]) {
        orderType = [[transferParas objectForKey:kOrderType] intValue];
        [transferParas removeObjectForKey:kOrderType];
    }
    
    // add BPush
    if ([url isEqualToString:login_URL]) {
        if (![XiangQuTool isStringEmpty:[USERDEFAULT objectForKey:kBPushUsrId]] && ![XiangQuTool isStringEmpty:[USERDEFAULT objectForKey:kBPushChannelId]] && ![XiangQuTool isStringEmpty:[USERDEFAULT objectForKey:kDeviceToken]]) {
            [transferParas setValue:[USERDEFAULT objectForKey:kBPushUsrId] forKey:kBPushUsrId];
            [transferParas setValue:[USERDEFAULT objectForKey:kDeviceToken] forKey:kDeviceToken];
            [transferParas setValue:[USERDEFAULT objectForKey:kBPushChannelId] forKey:kBPushChannelId];
        }
    }
    
    // uuid
    if ([url isEqualToString:getToken_URL]) {
        [transferParas setValue:[XiangQuTool getDeviceSN] forKey:@"deviceSN"];
    }
    
    NSString *requestURL = [NSString stringWithFormat:@"%@/%@",hostURL,url];
    [self actionAddOtherParas:transferParas];
    AFHTTPRequestOperation *operation = [self POST:requestURL parameters:transferParas success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (!noLoading) {
            // hide hud
            [[XiangQuToastManager manager] hideprogress];
        }        
#ifdef DEBUG
        NSLog(@"RESPONSE JSON:%@", responseObject);
#endif
        id<XiangQuParse> bodyParser = [[XiangQuParserFactory sharedInstance] parserWithURL:url];
        
        BOOL pullLoadingMore = [objc_getAssociatedObject(operation, &loadingmoreKey) boolValue];
        
        ((XiangQuBaseParser *)bodyParser).orderType = orderType;
        ((XiangQuBaseParser *)bodyParser).isLoadingMore = pullLoadingMore;
        
        [bodyParser parserBody:responseObject];
        
        success(operation,bodyParser);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (!noLoading) {
            // hide hud
            [[XiangQuToastManager manager] hideprogress];
        }
        failure(operation,error);
    }];
    objc_setAssociatedObject(operation, &loadingmoreKey, @(isLoadingMore), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    operation.urlTag = url;
    return operation;
}

#pragma mark -actionAddOtherParas
- (void)actionAddOtherParas:(NSMutableDictionary *)transferParas {
    NSString *currentUsrId = [USERDEFAULT objectForKey:kUsrId];
    NSString *timeStamp = [NSString stringWithFormat:@"%.f",([[NSDate date] timeIntervalSince1970]*1000)];
    NSString *timeStampKey = [[NSString stringWithFormat:@"%@%@",ktimeStmap,timeStamp] md5];
    
    [transferParas setValue:timeStamp forKey:@"t"];
    [transferParas setValue:timeStampKey forKey:@"key"];
    if ([XiangQuTool isStringEmpty:[transferParas objectForKey:@"userid"]]) {
        [transferParas setValue:currentUsrId forKey:@"userid"];
    }
}

#pragma mark -uploadDataWithURL
- (void)uploadDataWithURL:(NSString *)url
                    paras:(NSDictionary *)parasDict
            formatterData:(NSArray *)data
                  success:(void(^)(AFHTTPRequestOperation *operation,NSObject *parserObject))success
                  failure:(void(^)(AFHTTPRequestOperation *operation,NSError *requestErr))failure {
    
    NSMutableDictionary *transferParas = [parasDict mutableCopy];
    
    // Loading
    BOOL noLoading = [[transferParas objectForKey:kNoLoading] boolValue];
    [transferParas removeObjectForKey:kNoLoading];
    if (!noLoading) {
        // show hud
        [[XiangQuToastManager manager] showprogress];
    }
    
    // host Change
    BOOL fromHotShop = [[transferParas objectForKey:KHotShopURL] boolValue];
    NSString *hostURL = [XiangQuTool hostsHandlerUnderHostShop:fromHotShop];
    [transferParas removeObjectForKey:KHotShopURL];
    
    // refresh or LoadingMore
    BOOL isLoadingMore = [[transferParas objectForKey:kLoadingMore] boolValue];
    [transferParas removeObjectForKey:kLoadingMore];
    
    BOOL changeAvatar = [[transferParas valueForKey:kChangeAvatar] boolValue];
    [transferParas removeObjectForKey:kChangeAvatar];
    
    NSString *requestURL = [NSString stringWithFormat:@"%@/%@",hostURL,url];
    [self actionAddOtherParas:transferParas];
    
    AFHTTPRequestOperation *operation = [[XiangQuHttpClient manager] POST:requestURL parameters:transferParas  constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (int i = 0; i < data.count; i++) {
            NSObject *bodyData = [data objectAtIndex:i];
            if ([bodyData isKindOfClass:[NSString class]]) {
                if (changeAvatar) {
                    [formData appendPartWithFileURL:[NSURL fileURLWithPath:(NSString *)bodyData] name:@"image" fileName:@"avatar.jpg" mimeType:@"image/jpeg" error:nil];
                } else {
                    [formData appendPartWithFileURL:[NSURL fileURLWithPath:(NSString *)bodyData] name:@"images" fileName:@"post.jpg" mimeType:@"image/jpeg" error:nil];
                }
            } else if ([bodyData isKindOfClass:[NSData class]]) {
                if (changeAvatar) {
                    [formData appendPartWithFileData:(NSData *)bodyData name:@"image" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
                } else {
                    [formData appendPartWithFileData:(NSData *)bodyData name:@"images" fileName:@"post.jpg" mimeType:@"image/jpeg"];
                }
            }
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (!noLoading) {
            // hide hud
            [[XiangQuToastManager manager] hideprogress];
        }
        
#ifdef DEBUG
        NSLog(@"RESPONSE JSON:%@", responseObject);
#endif
        id<XiangQuParse> bodyParser = [[XiangQuParserFactory sharedInstance] parserWithURL:url];
        BOOL pullLoadingMore = [objc_getAssociatedObject(operation, &loadingmoreKey) boolValue];
        ((XiangQuBaseParser *)bodyParser).isLoadingMore = pullLoadingMore;
        [bodyParser parserBody:responseObject];
        success(operation,bodyParser);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (!noLoading) {
            // hide hud
            [[XiangQuToastManager manager] hideprogress];
        }
        
        failure(operation,error);
    }];
    objc_setAssociatedObject(operation, &loadingmoreKey, @(isLoadingMore), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    operation.urlTag = url;
}
@end
